import { UserInfo } from './entity/UserInfo'
/**
 * 缓存用户信息
 */
class CacheUserUtil {
    private static TOKEN_KEY: string = '__LMS__TOKEN__KEY__'
    private static REFRESH_TOKEN_KEY: string = '__LMS__REFRESH__TOKEN__KEY__'
    private static USER_INFO_KEY: string = '__LMS__USER__INFO__KEY__'

    static setToken(token: string) {
        sessionStorage.setItem(CacheUserUtil.TOKEN_KEY, token)
        CacheUserUtil.encode()
    }
    static getToken() {
        const token: string = sessionStorage.getItem(CacheUserUtil.TOKEN_KEY) as string
        if (token) return token
        return null
    }
    static setRefreshToken(token: string) {
        sessionStorage.setItem(CacheUserUtil.REFRESH_TOKEN_KEY, token)
    }
    static getRefreshToken() {
        const token: string = sessionStorage.getItem(CacheUserUtil.REFRESH_TOKEN_KEY) as string
        if (token) return token
        return null
    }
    private static encode() {
        // 解码token
        const token = CacheUserUtil.getToken()
        if (token === null) return
        const t = token.split(".")[1]
        const user = decodeURIComponent(escape(window.atob(t)))
        sessionStorage.setItem(CacheUserUtil.USER_INFO_KEY, user)
    }
    static getUserInfo(): UserInfo {
        const res = new UserInfo()
        const jsonStr = sessionStorage.getItem(CacheUserUtil.USER_INFO_KEY) ?? '{}'
        const user = JSON.parse(jsonStr)
        res.userId = user.userId ?? ''
        res.username = user.username ?? ''
        res.authorities = user._authorities ?? []
        return res
    }
    static clear() {
        sessionStorage.removeItem(CacheUserUtil.TOKEN_KEY)
        sessionStorage.removeItem(CacheUserUtil.REFRESH_TOKEN_KEY)
        sessionStorage.removeItem(CacheUserUtil.USER_INFO_KEY)
    }
}

export { CacheUserUtil }